<template>
  <view class="container">
    <view class="header">
      <view class="avatar-section">
        <image class="avatar" :src="userInfo.avatarUrl || defaultAvatarPath" mode="aspectFill" @tap="chooseAvatar"></image>
        <text class="tip">点击更换头像</text>
      </view>
    </view>

    <!-- 用户类型切换 -->
    <view class="form-group">
      <view class="form-item">
        <text class="label">用户类型</text>
        <picker :range="userTypeOptions" @change="onUserTypeChange" :value="userTypeIndex">
          <view class="picker">{{userTypeText}}{{userType === 'teacher' ? '(教师)' : '(学生)'}}</view>
        </picker>
      </view>
    </view>

    <view class="form-group">
      <!-- <view class="form-item">
        <text class="label">用户名</text>
        <input type="text" v-model="userInfo.username" placeholder="请输入用户名" :disabled="true"/>
      </view> -->
      
      <view class="form-item">
        <text class="label">昵称</text>
        <input type="text" v-model="userInfo.nickname" placeholder="请输入昵称"/>
      </view>

      <view class="form-item">
        <text class="label">性别</text>
        <picker :range="genderOptions" @change="onGenderChange" :value="genderIndex">
          <view class="picker">{{userInfo.gender || '请选择'}}</view>
        </picker>
      </view>

      <view class="form-item">
        <text class="label">手机号</text>
        <input type="number" v-model="userInfo.phone" placeholder="请输入手机号"/>
      </view>

      <view class="form-item">
        <text class="label">邮箱</text>
        <input type="text" v-model="userInfo.email" placeholder="请输入邮箱"/>
      </view>

      <view class="form-item">
        <text class="label">个性签名</text>
        <textarea v-model="userInfo.signature" placeholder="请输入个性签名" maxlength="100"/>
      </view>
    </view>

    <!-- 学生信息表单 -->
    <view class="form-group" v-show="userType === 'student'">
      <view class="form-title">学生信息</view>
      
      <view class="form-item">
        <text class="label">姓名</text>
        <input type="text" v-model="studentInfo.student_name" placeholder="请输入姓名"/>
      </view>
      
      <view class="form-item">
        <text class="label">性别</text>
        <picker :range="studentGenderOptions" @change="onStudentGenderChange" :value="studentGenderIndex">
          <view class="picker">{{studentInfo.gender_text || '请选择'}}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">班级</text>
        <input type="text" v-model="studentInfo.class_name" placeholder="请输入班级"/>
      </view>
      
      <view class="form-item">
        <text class="label">学号</text>
        <input type="text" v-model="studentInfo.student_number" placeholder="请输入学号"/>
      </view>
    </view>
    
    <!-- 教师信息表单 -->
    <view class="form-group" v-show="userType === 'teacher'">
      <view class="form-title">教师信息</view>
      
      <view class="form-item">
        <text class="label">教师姓名</text>
        <input type="text" v-model="teacherInfo.teacher_name" placeholder="请输入教师姓名"/>
      </view>
      
      <view class="form-item">
        <text class="label">职称</text>
        <picker :range="titleOptions" @change="onTitleChange" :value="titleIndex">
          <view class="picker">{{teacherInfo.professional_title || '请选择职称'}}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">所授课程</text>
        <picker :range="courseOptions" @change="onCourseChange" :value="courseIndex">
          <view class="picker">{{teacherInfo.courses_taught || '请选择课程'}}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">联系电话</text>
        <input type="number" v-model="teacherInfo.contact_phone" placeholder="请输入联系电话"/>
      </view>
      
      <view class="form-item form-tips">
        <text class="tips">ID将自动关联到您的用户账号</text>
      </view>
    </view>

    <view class="btn-group">
      <button class="save-btn" @tap="saveUserInfo">保存修改</button>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request'
import { BASE_URL, SERVICE_PREFIX } from '@/utils/request'

export default {
  data() {
    return {
      userInfo: {
        userId: '',
        username: '',
        nickname: '',
        avatarUrl: '',
        signature: '',
        phone: '',
        email: '',
        gender: null
      },
      genderOptions: ['男', '女'],
      genderIndex: -1,
      studentInfo: {
        student_name: '',
        gender_text: '',
        class_name: '',
        student_number: ''
      },
      studentGenderOptions: ['男', '女'],
      studentGenderIndex: -1,
      defaultAvatarPath: '/static/images/default-avatar.png',
      userType: '',
      teacherInfo: {
        teacher_name: '',
        professional_title: '',
        courses_taught: '',
        contact_phone: ''
      },
      titleOptions: ['教授', '副教授', '讲师', '助教', '高级教师', '中级教师', '初级教师'],
      titleIndex: -1,
      courseOptions: ['数学', '语文', '英语', '物理', '化学', '生物', '历史', '地理', '政治', '信息技术', '计算机科学', '体育', '音乐', '美术', '其他'],
      courseIndex: -1,
      userTypeOptions: ['学生', '教师'],
      userTypeIndex: -1,
      userTypeText: ''
    }
  },
  onLoad() {
    // 创建默认头像本地路径
    this.defaultAvatarPath = '/static/images/default-avatar.png';
    // 页面加载时获取用户信息
    this.loadUserInfo()
  },
  methods: {
    async loadUserInfo() {
      try {
        // 从本地存储获取用户ID
        const userInfoStorage = uni.getStorageSync('userInfo')
        if (!userInfoStorage || !userInfoStorage.userId) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
          return
        }

        console.log('当前用户ID:', userInfoStorage.userId)
        
        // 确定用户类型（从本地存储获取），默认为教师类型
        this.userType = uni.getStorageSync('userType') || 'teacher'
        console.log('当前用户类型:', this.userType)
        
        // 设置用户类型下拉框的值
        this.userTypeIndex = this.userType === 'student' ? 0 : 1
        this.userTypeText = this.userTypeOptions[this.userTypeIndex]
        
        // 显示加载中提示
        uni.showLoading({
          title: '加载中...'
        })

        try {
          // 先获取用户基本信息
          const userRes = await request.get('/api/student/getUserInfo', {
            userId: userInfoStorage.userId
          })
          
          console.log('获取用户信息响应:', userRes)
          
          // 处理用户基本信息
          if (userRes.code === 200) {
            this.userInfo = userRes.data
            
            // 设置性别选择器的索引
            this.genderIndex = this.genderOptions.indexOf(this.userInfo.gender)
          } else {
            uni.showToast({
              title: userRes.msg || '获取用户信息失败',
              icon: 'none'
            })
          }
          
          // 根据用户类型获取对应的角色信息
          if(this.userType === 'student') {
            // 获取学生信息
            try {
              // 调用学生信息专用接口
              const studentRes = await request.get('/api/student/getUserStudentInfo', {
                userId: userInfoStorage.userId
              })
              
              console.log('获取学生信息响应:', studentRes)
              
              // 处理学生信息，直接从接口返回的data中获取
              if (studentRes.code === 200 && studentRes.data) {
                const studentData = studentRes.data;
                console.log('接收到的学生信息原始数据:', studentData);
                
                // 转换后端返回的驼峰格式字段名到前端使用的下划线格式
                this.studentInfo = {
                  student_name: studentData.studentName || '',
                  gender_text: studentData.gender === 1 ? '男' : (studentData.gender === 2 ? '女' : ''),
                  class_name: studentData.className || '',  // 使用className字段
                  student_number: studentData.studentNumber || ''
                }
                
                console.log('转换后的学生信息:', this.studentInfo)
                
                // 设置学生性别选择器的索引
                this.studentGenderIndex = this.studentGenderOptions.indexOf(this.studentInfo.gender_text)
              }
            } catch (studentError) {
              console.error('获取学生信息失败，但不影响基本功能:', studentError)
              // 不显示错误提示，让用户仍然可以使用基本功能
            }
          } else if(this.userType === 'teacher') {
            // 获取教师信息
            try {
              // 调用教师信息专用接口
              const teacherRes = await request.get('/api/teacher/getUserTeacherInfo', {
                userId: userInfoStorage.userId
              })
              
              console.log('获取教师信息响应:', teacherRes)
              
              // 处理教师信息
              if (teacherRes.code === 200 && teacherRes.data) {
                const teacherData = teacherRes.data;
                console.log('接收到的教师信息原始数据:', teacherData);
                
                // 转换后端返回的驼峰格式字段名到前端使用的下划线格式
                this.teacherInfo = {
                  teacher_name: teacherData.teacherName || '',
                  professional_title: teacherData.professionalTitle || '',
                  courses_taught: teacherData.coursesTaught || '',
                  contact_phone: teacherData.contactPhone || ''
                }
                
                console.log('转换后的教师信息:', this.teacherInfo)
                
                // 设置教师职称选择器的索引
                this.titleIndex = this.titleOptions.indexOf(this.teacherInfo.professional_title)
                this.courseIndex = this.courseOptions.indexOf(this.teacherInfo.courses_taught)
              }
            } catch (teacherError) {
              console.error('获取教师信息失败，但不影响基本功能:', teacherError)
              // 不显示错误提示，让用户仍然可以使用基本功能
            }
          }
          
          // 完成所有加载后隐藏加载提示
          uni.hideLoading()
        } catch (error) {
          uni.hideLoading()
          console.error('加载信息失败:', error)
          uni.showToast({
            title: '获取信息失败',
            icon: 'none'
          })
        }
        
      } catch (error) {
        // 确保错误时也隐藏加载提示
        try { uni.hideLoading() } catch(e) {}
        
        console.error('加载用户信息总体失败:', error)
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      }
    },

    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          
          // 显示上传中提示
          uni.showLoading({
            title: '上传中...'
          })
          
          // 先尝试标准的文件上传方式
          this.uploadAvatar(tempFilePath)
            .catch(error => {
              console.log('标准上传失败，尝试备用上传方式', error)
              // 如果标准上传失败，尝试Base64上传
              return this.uploadAvatarAsBase64(tempFilePath)
            })
            .then(avatarUrl => {
              // 设置新的头像URL
              this.userInfo.avatarUrl = avatarUrl
              
              uni.hideLoading()
              uni.showToast({
                title: '头像更新成功',
                icon: 'success'
              })
            })
            .catch(error => {
              uni.hideLoading()
              console.error('所有上传方式均失败:', error)
              uni.showToast({
                title: '头像上传失败: ' + (error.message || '未知错误'),
                icon: 'none'
              })
            })
        }
      })
    },
    
    // 标准的文件上传方法
    uploadAvatar(filePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: BASE_URL + '/api/student/updateAvatarUrl',
          filePath: filePath,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
            'Accept': '*/*'
          },
          formData: {
            userId: this.userInfo.userId
          },
          success: (uploadRes) => {
            console.log('上传响应原始数据:', uploadRes)
            
            try {
              const result = JSON.parse(uploadRes.data)
              console.log('头像上传结果:', result)
              
              if (result.code === 200) {
                resolve(result.data)
              } else {
                reject(new Error(result.msg || '上传失败'))
              }
            } catch (e) {
              console.error('解析上传结果失败:', e, uploadRes.data)
              reject(new Error('返回格式错误'))
            }
          },
          fail: (err) => {
            console.error('头像上传失败:', err)
            reject(err)
          }
        })
      })
    },

    onGenderChange(e) {
      this.genderIndex = e.detail.value
      this.userInfo.gender = this.genderOptions[this.genderIndex]
    },

    async saveUserInfo() {
      try {
        // 表单验证
        if (this.userInfo.phone && !/^1[3-9]\d{9}$/.test(this.userInfo.phone)) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
          })
          return
        }

        if (this.userInfo.email && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(this.userInfo.email)) {
          uni.showToast({
            title: '请输入正确的邮箱',
            icon: 'none'
          })
          return
        }

        // 学生信息验证
        if (this.userType === 'student' && this.studentInfo.student_number && !this.studentInfo.student_name) {
          uni.showToast({
            title: '请填写学生姓名',
            icon: 'none'
          })
          return
        }
        
        // 教师信息验证
        if (this.userType === 'teacher') {
          if (!this.teacherInfo.teacher_name) {
            uni.showToast({
              title: '教师姓名不能为空',
              icon: 'none'
            })
            return
          }
        }

        console.log('准备提交的用户信息:', this.userInfo)
        if (this.userType === 'student') {
          console.log('准备提交的学生信息:', this.studentInfo)
        } else {
          console.log('准备提交的教师信息:', this.teacherInfo)
        }
        
        // 显示加载中提示
        uni.showLoading({
          title: '保存中...'
        })

        // 准备提交的用户数据
        const updateData = {
          userId: this.userInfo.userId,
          username: this.userInfo.username,
          nickname: this.userInfo.nickname,
          phone: this.userInfo.phone,
          email: this.userInfo.email,
          signature: this.userInfo.signature,
          gender: this.userInfo.gender,
          avatarUrl: this.userInfo.avatarUrl
        }

        // 添加调试信息
        console.log('提交的用户数据:', JSON.stringify(updateData))

        // 提交用户基本信息
        const userRes = await request.post('/api/student/updateUserInfo', updateData)
        
        if (userRes.code !== 200) {
          uni.hideLoading()
          uni.showToast({
            title: userRes.msg || '保存用户信息失败',
            icon: 'none'
          })
          return
        }
        
        // 根据用户类型提交对应的信息
        if (this.userType === 'student') {
          // 如果填写了学生信息，则提交学生信息
          if (this.studentInfo.student_name || this.studentInfo.student_number) {
            // 转换性别格式 (男=1, 女=2)
            let studentGender = null
            if (this.studentInfo.gender_text === '男') {
              studentGender = 1
            } else if (this.studentInfo.gender_text === '女') {
              studentGender = 2
            }
            
            // 调用学生信息更新接口，参照用户提供的接口
            const studentData = {
              // 将学生信息包装到SysStudent对象中，符合接口要求格式
              studentName: this.studentInfo.student_name,
              gender: studentGender,
              classId: null, // 暂时为空，实际应该从班级列表中选择
              studentNumber: this.studentInfo.student_number,
              className: this.studentInfo.class_name, // 添加班级名称字段
              id: this.userInfo.userId // 添加用户ID，不然无法关联到要修改的用户
            }
            
            console.log('提交的学生数据(JSON):', JSON.stringify(studentData))
            
            // 调用学生信息更新接口，参照用户提供的接口
            const studentRes = await request.post('/api/student/updateStudentInfo', studentData)
            
            if (studentRes.code !== 200) {
              uni.hideLoading()
              uni.showToast({
                title: studentRes.msg || '保存学生信息失败',
                icon: 'none'
              })
              return
            }
          }
        } else if (this.userType === 'teacher') {
          // 如果填写了教师信息，则提交教师信息
          if (this.teacherInfo.teacher_name || this.teacherInfo.contact_phone) {
            // 调用教师信息更新接口
            const teacherData = {
              // 字段名与Java实体类完全匹配(驼峰命名法)
              id: this.userInfo.userId, // 使用用户ID作为教师ID
              teacherName: this.teacherInfo.teacher_name,
              professionalTitle: this.teacherInfo.professional_title,
              coursesTaught: this.teacherInfo.courses_taught,
              contactPhone: this.teacherInfo.contact_phone
            }
            
            console.log('提交的教师数据(JSON):', JSON.stringify(teacherData))
            console.log('教师姓名:', teacherData.teacherName)
            console.log('职称:', teacherData.professionalTitle)
            console.log('所授课程:', teacherData.coursesTaught)
            console.log('联系电话:', teacherData.contactPhone)
            
            // 调用教师信息更新接口
            const teacherRes = await request.post('/api/teacher/updateTeacherInfo', teacherData)
            
            if (teacherRes.code !== 200) {
              uni.hideLoading()
              uni.showToast({
                title: teacherRes.msg || '保存教师信息失败',
                icon: 'none'
              })
              return
            }
          }
        }

        uni.hideLoading()
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        // 更新本地存储的用户信息
        const storageUserInfo = uni.getStorageSync('userInfo')
        if (storageUserInfo) {
          const updatedUserInfo = {
            ...storageUserInfo,
            ...updateData
          }
          uni.setStorageSync('userInfo', updatedUserInfo)
        }
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        uni.hideLoading()
        console.error('保存用户信息失败:', error)
        uni.showToast({
          title: '保存失败: ' + (error.message || JSON.stringify(error)),
          icon: 'none'
        })
      }
    },
    
    // Base64头像上传方法
    async uploadAvatarAsBase64(filePath) {
      return new Promise((resolve, reject) => {
        // 读取图片为base64
        uni.getFileSystemManager().readFile({
          filePath: filePath,
          encoding: 'base64',
          success: async (res) => {
            try {
              const base64Data = res.data
              
              // 调用后端API上传base64图片
              const uploadRes = await request.post('/api/student/uploadBase64Avatar', {
                userId: this.userInfo.userId,
                imageData: base64Data,
                fileName: `avatar_${Date.now()}.jpg`
              })
              
              if (uploadRes.code === 200) {
                resolve(uploadRes.data)
              } else {
                reject(new Error(uploadRes.msg || '上传失败'))
              }
            } catch (err) {
              reject(err)
            }
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    },

    onStudentGenderChange(e) {
      this.studentGenderIndex = e.detail.value
      this.studentInfo.gender_text = this.studentGenderOptions[this.studentGenderIndex]
    },

    onTitleChange(e) {
      this.titleIndex = e.detail.value
      this.teacherInfo.professional_title = this.titleOptions[this.titleIndex]
    },

    onCourseChange(e) {
      this.courseIndex = e.detail.value
      this.teacherInfo.courses_taught = this.courseOptions[this.courseIndex]
    },

    onUserTypeChange(e) {
      this.userTypeIndex = e.detail.value
      this.userTypeText = this.userTypeOptions[this.userTypeIndex]
      // 转换为后端识别的类型值
      this.userType = this.userTypeIndex == 0 ? 'student' : 'teacher'
      console.log('用户切换为:', this.userType)
      
      // 保存到本地存储
      uni.setStorageSync('userType', this.userType)
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f6f6f6;
  padding: 20rpx;
}

.header {
  background: #fff;
  padding: 40rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  
  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .avatar {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
      margin-bottom: 20rpx;
    }
    
    .tip {
      font-size: 28rpx;
      color: #999;
    }
  }
}

.form-group {
  background: #fff;
  border-radius: 12rpx;
  padding: 0 30rpx;
  
  .form-item {
    display: flex;
    align-items: center;
    min-height: 100rpx;
    border-bottom: 1rpx solid #eee;
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      width: 160rpx;
      font-size: 28rpx;
      color: #333;
    }
    
    input, .picker {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
    
    textarea {
      flex: 1;
      height: 160rpx;
      font-size: 28rpx;
      padding: 20rpx 0;
    }
  }
  
  .form-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #4080ff;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;
    margin-bottom: 10rpx;
  }
}

.form-tips {
    display: flex;
    justify-content: center;
    padding: 10rpx 0;
    
    .tips {
      font-size: 24rpx;
      color: #999;
      font-style: italic;
    }
  }

.btn-group {
  margin-top: 60rpx;
  padding: 0 30rpx;
  
  .save-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: #4080ff;
    color: #fff;
    font-size: 32rpx;
    border-radius: 44rpx;
    text-align: center;
    
    &:active {
      background: #3070e0;
    }
  }
}
</style> 